const db = require("../db/index");
const bcrypt = require("bcryptjs");
// 获取用户信息
exports.getUserInfo = (req, res) => {
  const sql = `select id,username,nickname,email,user_pic from ev_users where id=?`;
  db.query(sql, req.auth.id, (err, results) => {
    if (err) return res.cc(err);
    if (results.length !== 1) return res.cc("获取用户信息失败");
    res.send({
      status: 0,
      message: "获取用户信息成功",
      data: results[0],
    });
  });
};

// 更新用户信息
exports.updateUserInfo = (req, res) => {
  const sql = `update ev_users set ? where id=?`;
  db.query(
    sql,
    [
      {
        nickname: req.body.nickname,
        email: req.body.email,
        user_pic: req.body.user_pic,
      },
      req.auth.id,
    ],
    (err, results) => {
      if (err) return res.cc(err);
      if (results.affectedRows !== 1) return res.cc("更新用户信息失败");
      res.cc("更新用户信息成功", 0);
    }
  );
};

// 更新密码
exports.updatePwd = (req, res) => {
  const sql = `select * from ev_users where id=?`;
  db.query(sql, req.auth.id, (err, results) => {
    const isPasswordCorrect = bcrypt.compareSync(
      req.body.oldPassword,
      results[0].password
    );
    if (!isPasswordCorrect) return res.cc("旧密码错误");
    const sql1 = `update ev_users set password=? where id=?`;
    db.query(
      sql1,
      [bcrypt.hashSync(req.body.newPassword, 10), req.auth.id],
      (err, results) => {
        if (err) return res.cc(err);
        if (results.affectedRows !== 1) return res.cc("更新密码失败");
        res.cc("更新密码成功", 0);
      }
    );
  });
};
